package cl.uchile.coupling.web.controllers;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cl.uchile.cos.session.Client;
import cl.uchile.cos.session.Session;
import cl.uchile.cos.session.SessionManager;

@Controller
@RequestMapping("/session")
public class AccessController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Autowired
	private Client client;
	@Autowired
	private SessionManager sessionManager;

	
	@RequestMapping(value="join/{ssid}", method = RequestMethod.POST,produces="application/json")
	public @ResponseBody String joinSession(@PathVariable String ssid) {
		Session session = null;
		if (ssid == null)
			session = sessionManager.createSession();
		else
			session = sessionManager.getSessionById(ssid.toString());
		sessionManager.joinClientToSession(client, session);
		return "{\"client_id\":"+client.getId()+", \"session_id\":\""+session.getSessionId()+"\"}";
	}
	
	@RequestMapping(value="leave/{ssid}", method = RequestMethod.POST)
	private @ResponseBody void leaveSession(@PathVariable String ssid) {
		
		Session session=sessionManager.getSessionById(ssid.toString());
		sessionManager.removeClientFromSession(client,session);
	}

}
